# app/services/base/base_service.py
"""
基础业务服务类
提供通用的业务逻辑和数据操作功能
"""
from typing import Optional, Type, List, Tuple, Any, Dict
from tortoise.models import Model
from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.core.user import CTX_USER_ID
from app.core.exceptions import BusinessError
  
from app.schemas.base.error_code import *

class BaseServiceMixin:
    """基础业务混入类"""
    
    async def get_safe(self, id: int) -> Model:
        """
        安全获取资源，不存在时抛出业务异常
        """
        try:
            item = await self.get(id=id)  # 调用 CRUDBase 的方法
            if not item or (hasattr(item, 'is_deleted') and item.is_deleted):
                raise BusinessError(RESOURCE_NOT_FOUND,details="资源不存在(软删除)")
            return item
        except Exception as e:
            raise BusinessError(RESOURCE_NOT_FOUND,f"获取资源失败: {str(e)}")
    
    async def exists(self, **filters) -> bool:
        """
        检查资源是否存在
        """
        try:
            if hasattr(self, 'model'):
                count = await self.model.filter(**filters).count()
                return count > 0
            return False
        except Exception:
            return False
    
    async def validate_and_create(self, obj_data: Dict[str, Any]) -> Model:
        """
        验证并创建资源
        """
        try:
            data = await self.create(obj_data)
            return data
        except Exception as e:
            raise BusinessError(RESOURCE_CREATE_FAILED,details=f"创建失败: {str(e)}")
    
    async def validate_and_update(self, id: int, obj_data: Dict[str, Any]) -> Model:
        """ 验证并更新资源 """
        try:
            # 先检查资源存在
            await self.get_safe(id)
            return await self.update(id, obj_data)
        except Exception as e:
            raise BusinessError(RESOURCE_UPDATE_FAILED,details = f"更新失败: {str(e)}")



class UserIsolationMixin:
    """用户隔离混入类"""
    
    async def _get_current_user_id(self, user_id: Optional[int] = None) -> int:
        """
        获取当前用户ID
        """
        if user_id is not None:
            return user_id
        return CTX_USER_ID.get()
    
    async def _add_user_filter(self, base_q: Optional[Q] = None, user_id: Optional[int] = None, field_name: str = "user_id") -> Q:
        """ 添加用户过滤条件"""
        user_id = 1
        current_user_id = await self._get_current_user_id(user_id)
        user_filter = Q(**{field_name: current_user_id})
        return base_q & user_filter if base_q else user_filter


class BaseService(CRUDBase, BaseServiceMixin, UserIsolationMixin):
    """
    基础业务服务类  继承CRUDBase并融合业务功能
    """
    def __init__(self, model: Type[Model], resource_name: str = "资源"):
        super().__init__(model)
        self.resource_name = resource_name
    
    async def list_by_user(
        self,
        page: int = 1,
        page_size: int = 10,
        search: Optional[Q] = None,
        order: Optional[List[str]] = None,
        user_id: Optional[int] = None,
        user_field: str = "user_id"
    ) -> Tuple[int, List]:
        """获取当前用户的资源列表"""
        user_filtered_q = self._add_user_filter(search, user_id, user_field)
        return await self.list(page, page_size, user_filtered_q, order or ['-created_at'])
    
    async def get_by_user(self, id: int, user_id: Optional[int] = None, user_field: str = "user_id"):
        """  获取当前用户的指定资源 """
        user_id = self._get_current_user_id(user_id)
        return await self.model.filter(id=id, **{user_field: user_id}).first()
    
    async def delete_by_user(self, id: int, user_id: Optional[int] = None, user_field: str = "user_id") -> bool:
        """
        删除当前用户的资源 ？是否删除成功
        """
        item = await self.get_by_user(id, user_id, user_field)
        if item:
            await item.delete()
            return True
        return False